﻿using LeEdu.DTO;
using LeEdu.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeEdu.UI.Controllers
{
    public class AdminController : Controller
    {
        private InstallService installService;
        private CourseService courseService;
        private FileService fileService;
        private HourService hourService;

        public AdminController()
        {
            installService = new InstallService();
            courseService = new CourseService();
            fileService = new FileService();
            hourService = new HourService();
        }

        public ActionResult Index()
        {
            return View();
        }

        #region 安装程序

        /// <summary>
        /// 安装程序
        /// </summary>
        /// <returns></returns>
        public ActionResult Install()
        {
            var rtv= installService.Initial();
            if(rtv)
            {
                return Content("数据库初始化成功！" + DateTime.Now);
            }
            return Content("数据库初始化失败！" + DateTime.Now);
        }

        #endregion

        #region 管理员管理

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string usr,string pwd)
        {
            //if(usr=="admin" && pwd=="admin")
            //{
                return RedirectToAction("Index");
            //}
        }

        public ActionResult LoginOut()
        {
            return RedirectToAction("Login");
        }

        #endregion

        #region 课程管理

        /// <summary>
        /// 课程管理（首页）
        /// </summary>
        /// <returns></returns>
        public ActionResult CourseManager(int pageIndex = 1)
        {
            var pageSize = 5;
            long totalSize = 0;
            var courses = courseService.GetCourses(pageIndex, pageSize, out totalSize);

            ViewBag.TotalPage = (int)Math.Ceiling((double)totalSize / (double)pageSize);
            ViewBag.PageIndex = pageIndex;
            ViewBag.Courses = courses;
            ViewBag.PageSize = pageSize;

            return View();
        }

        

        /// <summary>
        /// 添加课程
        /// </summary>
        /// <param name="name"></param>
        /// <param name="des"></param>
        /// <returns></returns>
        
        [HttpPost]
        public ActionResult AddCourse(string name,string des)
        {                        
            var course = new LeEdu.Entity.Course()
            {
                Id=Guid.NewGuid(),
                Name=name,
                Description=des,
                CreateTime=DateTime.Now,               
            };

            var result = courseService.AddCourse(course);
            if(result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
           else
            {
                return Json(new { Code =0, Msg = "处理失败！" });
            }
        }

        public ActionResult DelCourse(Guid cid)
        {
            var result = courseService.DelCourse(cid);
            if (result)
            {
                return Content("<script>location.href='/Admin/CourseManager'</script>");
            }
            else
            {
                return Content("<script>alert('处理失败！')</script>");
            }
            
        }
        /// <summary>
        /// 通过课程ID获取课程信息，编辑操作的前一步
        /// </summary>
        /// <param name="cid">课程ID</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetCourseById(Guid cid)
        {             
            Course courses = courseService.GetCourseById(cid);
            return Json(courses);            
        }

        /// <summary>
        /// 编辑课程信息
        /// </summary>
        /// <param name="name">课程名称</param>
        /// <param name="des">课程描述</param>
        /// <param name="cid">课程Id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditCourse(string name, string des,Guid cid)
        {
            Course course = courseService.GetCourseById(cid);
            course.Name = name;
            course.Description = des;

            var result = courseService.EditCourse(course);
            if (result)
            {
                return Json(new { Code = 1, Msg = "处理成功！" });
            }
            else
            {
                return Json(new { Code = 0, Msg = "处理失败！" });
            }
        }
        #endregion

        /// <summary>
        /// 课程设置
        /// </summary>
        /// <returns></returns>
        public ActionResult Course(Guid cid)
        {
            Course course = courseService.GetCourseById(cid);
            ViewBag.CourseName = course.Name;
            ViewBag.CourseId = cid;
            return View();
        }


        public ActionResult CourseImgUpload(Guid cid)
        {
            var folderPath = Path.Combine("Uploads\\Courses\\CoursesImg", cid.ToString());
            FileInfo fileInfo;            
            Common.FileUploadHelper.Save(Request, folderPath, out fileInfo);
            var length = fileInfo.Length;
            //var newpath = Path.Combine("\\"+folderPath + "\\course_thump_" + cid.ToString());
            
            var oldsrc = Server.MapPath("/Uploads/Courses/CoursesImg/"+cid.ToString()+"/"+fileInfo.Name);
            var newsrc = Server.MapPath("/Uploads/Courses/CoursesImg/" + cid.ToString() + "/" + "course_thump_" + cid.ToString()+fileInfo.Extension);
            System.IO.File.Move(oldsrc,newsrc);
            
            if (null != fileInfo)
            {
                DTO.File file = new DTO.File();
                file.Id = Guid.NewGuid();
                file.CourseId = cid;
                file.CreateTime = fileInfo.CreationTime;
                file.Name = "course_thump_" + cid.ToString();               
                file.Length = length;
                file.StorageType = 0;//存储类型
                //file.UpdateUserId
                file.Used = true;
                file.Extension = fileInfo.Extension;
                fileService.Add(file);
                Course course = courseService.GetCourseById(cid);
                course.ImgUrl = "/Uploads/Courses/CoursesImg/" + file.CourseId + "/" + "course_thump_" + file.CourseId + file.Extension;
                courseService.EditCourse(course);
            }
            return null;
        }
        

        /// <summary>
        /// 文件管理
        /// </summary>
        /// <returns></returns>
        public ActionResult FileManager(Guid cid)
        {
            Course course = courseService.GetCourseById(cid);
            ViewBag.CourseName = course.Name;
            ViewBag.CourseId = cid;

            var files= fileService.List(cid);
            ViewBag.Files = files;
            
            return View();
            
        }

        public ActionResult FileUpload(Guid cid)
        {
            var folderPath = Path.Combine("Uploads\\Courses", cid.ToString());
            FileInfo fileInfo;
            Common.FileUploadHelper.Save(Request, folderPath, out fileInfo);

            if(null!=fileInfo)
            {
                DTO.File file = new DTO.File();
                file.Id = Guid.NewGuid();
                file.CourseId = cid;
                file.CreateTime = fileInfo.CreationTime;
                file.Name = fileInfo.Name;
                file.Length = fileInfo.Length;
                file.StorageType = 0;//存储类型
                //file.UpdateUserId
                file.Used = false;
                file.Extension = fileInfo.Extension;

                fileService.Add(file);
            }
            
            return null;
        }

        



        

        #region 课时管理
        /// <summary>
        /// 课时管理
        /// </summary>
        /// <returns></returns>
        public ActionResult ClassHour(Guid cid)
        {
            Course course = courseService.GetCourseById(cid);
            ViewBag.CourseName = course.Name;
            var hours = hourService.GetNodeList(cid);
            ViewBag.Hours = hours;
            ViewBag.CourseId = cid;//课程Id
            var files = fileService.SelectListByCourseIdAndDocType(cid);
            ViewBag.Files = files;
            return View();
        }
        /// <summary>
        /// 为课时绑定教学视频
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool VideoBind(Guid cid, string fname,Guid hid,Guid fid)
        {
            var HourUrl = "/Uploads/Courses/" + cid + "/" + fname;
            var hour = hourService.GetHourById(hid);
            hour.VideoUrl = HourUrl;
            LeEdu.DTO.File file_ = fileService.SelectFileByFileId(fid);
            file_.Used = true;
            return hourService.EditHour(hour) && fileService.Edit(file_);
        }
        /// <summary>
        /// 显示课时列表
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public List<Node> GetNodeList(Guid uid)
        {
            return hourService.GetNodeList(uid);
        }

        /// <summary>
        /// 课时排序
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public bool NodeSort(string[] ids)
        {
            var rtv = hourService.UpdateNodeSort(ids);
            return rtv;
        }

        /// <summary>
        /// 添加章
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>

        public bool AddChapter(string courseId, string title)
        {
            return hourService.AddNode(courseId, title,NodeType.Chapter);
        }
        /// <summary>
        /// 添加节
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public bool AddSection(string courseId, string title)
        {
            return hourService.AddSection(courseId, title);            
        }
        /// <summary>
        /// 添加课时
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool AddHour(Guid courseId, string title)
        {
            return hourService.AddHour(courseId, title);
        }

        /// <summary>
        /// 删除章/节
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelNode(Guid id)
        {
            return hourService.DelNode(id);
        }
        /// <summary>
        /// 删除课时
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelHour(Guid id)
        {
            return hourService.DelHour(id);
        }

        #endregion
    }
}